package com.yyj.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.mysql.fabric.proto.xmlrpc.AuthenticatedXmlRpcMethodCaller;
import com.yyj.dao.TPropertyRepairRecordItemMapper;
import com.yyj.dao.TPropertyRepairRecordMapper;
import com.yyj.enums.RepairRecordStatusEnum;
import com.yyj.exception.BaseException;
import com.yyj.model.TPropertyOwner;
import com.yyj.model.TPropertyRepairRecord;
import com.yyj.model.TPropertyRepairRecordItem;
import com.yyj.model.TPropertyRepairRecordItemExample;
import com.yyj.web.controller.BaseController;
import com.yyj.web.protocol.PageRequest;
import com.yyj.web.protocol.PageRspData;
import com.yyj.web.protocol.req.*;
import com.yyj.web.protocol.resp.RepairRecordResp;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class RepairRecordService {

    public static final Logger logger = LoggerFactory.getLogger(RepairRecordService.class);


    @Autowired
    TPropertyRepairRecordMapper repairRecordMapper;

    @Autowired
    TPropertyRepairRecordItemMapper repairRecordItemMapper;

    @Autowired
    UserService userService;

    @Autowired
    PushMessageService pushMessageService;


    @Transactional(rollbackFor = Exception.class)
    public void submitRepairRecord(RepairRecordReq repairRecordReq) throws Exception{
        TPropertyRepairRecord repairRecord = new TPropertyRepairRecord();
        TPropertyOwner propertyOwner = userService.findOwnerByMobile(repairRecordReq.getMobile() , repairRecordReq.getRoomNum());
        if(null == propertyOwner){
            throw new BaseException("用户不存在");
        }
        repairRecord.setContent(repairRecordReq.getContent());
        repairRecord.setCreator(propertyOwner.getId());
        repairRecord.setRoomNum(repairRecordReq.getRoomNum());
        repairRecord.setMobile(repairRecordReq.getMobile());
        repairRecord.setCreateTime(new Date());
        repairRecord.setUpdateTime(new Date());
        repairRecord.setStatus(RepairRecordStatusEnum.WAITING_FOLLOW.getCode());
        int insertRlt = repairRecordMapper.insert(repairRecord);
        if(1 == insertRlt){
            for(String imgUrl : repairRecordReq.getImgUrls()){
                TPropertyRepairRecordItem repairRecordItem = new TPropertyRepairRecordItem();
                repairRecordItem.setRecordId(repairRecord.getId());
                repairRecordItem.setImgUrl(imgUrl);
                repairRecordItemMapper.insert(repairRecordItem);
            }
            PushRepairOrderReq pushRepairOrderReq = new PushRepairOrderReq();
            pushRepairOrderReq.setId(repairRecord.getId());
            pushRepairOrderReq.setContent(repairRecord.getContent());
            pushRepairOrderReq.setCreateTime(repairRecord.getCreateTime());
            pushRepairOrderReq.setMobile(repairRecordReq.getMobile());
            pushRepairOrderReq.setRoomNum(repairRecord.getRoomNum());
            pushMessageService.pushRepairOrderToManager(pushRepairOrderReq);
        }

    }

    public PageRspData<RepairRecordResp> queryRepairRecords(RepairRecordQueryReq repairRecordQueryReq){
        Page page = PageHelper.startPage(repairRecordQueryReq.getCurrentPage(), repairRecordQueryReq.getPageSize());
        List<RepairRecordResp> repairRecordRespList = Lists.newArrayList();
        List<TPropertyRepairRecord> ownerRepairRecordList = repairRecordMapper.queryOwnerRepairRecord(repairRecordQueryReq);
        for(TPropertyRepairRecord repairRecord : ownerRepairRecordList){
            RepairRecordResp repairRecordResp = new RepairRecordResp();
            repairRecordResp.setId(repairRecord.getId());
            repairRecordResp.setContent(repairRecord.getContent());
            repairRecordResp.setCreateTime(repairRecord.getCreateTime());
            repairRecordResp.setStatus(repairRecord.getStatus());
            repairRecordResp.setRoomNum(repairRecord.getRoomNum());
            repairRecordResp.setMobile(repairRecord.getMobile());
            repairRecordResp.setRemark(repairRecord.getRemark());
            repairRecordResp.setFollowStatement1(repairRecord.getFollowStatement1());
            repairRecordResp.setFollowStatement2(repairRecord.getFollowStatement2());
            repairRecordResp.setOwnerReply(repairRecord.getOwnerReply());
            long recordId = repairRecord.getId();
            List<TPropertyRepairRecordItem> repairRecordItems = queryRepairRecordItems(recordId);
            List<String> imgUrls = Lists.newArrayList();
            for(TPropertyRepairRecordItem repairRecordItem : repairRecordItems){
                imgUrls.add(repairRecordItem.getImgUrl());
            }
            repairRecordResp.setImgUrls(imgUrls);
            repairRecordRespList.add(repairRecordResp);
        }

        PageRspData<RepairRecordResp> pageRspData = new PageRspData<RepairRecordResp>(
                page.getTotal(), repairRecordQueryReq.getCurrentPage(), repairRecordQueryReq.getPageSize(), repairRecordRespList);
        return pageRspData;
    }

    private List<TPropertyRepairRecordItem> queryRepairRecordItems(long recordId){
        TPropertyRepairRecordItemExample repairRecordItemExample = new TPropertyRepairRecordItemExample();
        TPropertyRepairRecordItemExample.Criteria criteria = repairRecordItemExample.createCriteria();
        criteria.andRecordIdEqualTo(recordId);
        List<TPropertyRepairRecordItem> list = repairRecordItemMapper.selectByExample(repairRecordItemExample);
        return list;
    }

    public RepairRecordResp queryRepairRecordResp(long id){
        RepairRecordResp repairRecordResp = new RepairRecordResp();
        TPropertyRepairRecord repairRecord = repairRecordMapper.selectByPrimaryKey(id);
        repairRecordResp.setId(repairRecord.getId());
        repairRecordResp.setMobile(repairRecord.getMobile());
        repairRecordResp.setRoomNum(repairRecord.getRoomNum());
        repairRecordResp.setStatus(repairRecord.getStatus());
        repairRecordResp.setCreateTime(repairRecord.getCreateTime());
        repairRecordResp.setContent(repairRecord.getContent());
        repairRecordResp.setRemark(repairRecord.getRemark());
        repairRecordResp.setFollowStatement1(repairRecord.getFollowStatement1());
        repairRecordResp.setFollowStatement2(repairRecord.getFollowStatement2());
        repairRecordResp.setOwnerReply(repairRecord.getOwnerReply());
        List<TPropertyRepairRecordItem> repairRecordItems = queryRepairRecordItems(id);
        List<String> imgUrls = Lists.newArrayList();
        for(TPropertyRepairRecordItem repairRecordItem : repairRecordItems){
            imgUrls.add(repairRecordItem.getImgUrl());
        }
        repairRecordResp.setImgUrls(imgUrls);

        return repairRecordResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public RepairRecordResp updateStatus(RepairStatusUpdateReq repairStatusUpdateReq) throws Exception{
        TPropertyRepairRecord repairRecord = repairRecordMapper.selectByPrimaryKey(repairStatusUpdateReq.getId());
        if(null == repairRecord){
            throw new BaseException("记录不存在");
        }
        repairRecord.setStatus(repairStatusUpdateReq.getStatus());
        repairRecord.setUpdateTime(new Date());
        /*String repairStatement = "";
        if(RepairRecordStatusEnum.IS_FOLLOW.getCode().equals(repairStatusUpdateReq.getStatus())){
            repairStatement = "师傅跟进中";
        }
        if(RepairRecordStatusEnum.IS_DEAL.getCode().equals(repairStatusUpdateReq.getStatus())){
            repairStatement = "你的报修师傅已经处理，如有疑问，请联系物业";
        }*/
        if(StringUtils.isNotBlank(repairStatusUpdateReq.getFollowStatement()) && StringUtils.isBlank(repairRecord.getFollowStatement1())){
            repairRecord.setFollowStatement1(repairStatusUpdateReq.getFollowStatement());
        }
        int updateRlt = repairRecordMapper.updateByPrimaryKeySelective(repairRecord);
        if(1 == updateRlt){
            try{
                PushMsgRepairReq pushMsgRepairReq = new PushMsgRepairReq();
                BeanUtils.copyProperties(repairRecord , pushMsgRepairReq);
                pushMsgRepairReq.setRepairStatement(repairStatusUpdateReq.getFollowStatement());
                pushMessageService.pushRepairResultToOwners(pushMsgRepairReq);
            }catch (Exception  e){
                logger.error("pushRepairResultToOwners error:{}" , e.getMessage() , e);
            }
        }
        RepairRecordResp repairRecordResp = new RepairRecordResp();
        BeanUtils.copyProperties(repairRecord , repairRecordResp);
        return repairRecordResp;

    }

    @Transactional(rollbackFor = Exception.class)
    public RepairRecordResp ownerReply(RepairReplyReq repairReplyReq) throws Exception {
        TPropertyRepairRecord repairRecord = repairRecordMapper.selectByPrimaryKey(repairReplyReq.getId());
        if (null == repairRecord) {
            throw new BaseException("记录不存在");
        }
        repairRecord.setOwnerReply(repairReplyReq.getReplyStatement());
        repairRecord.setUpdateTime(new Date());
        repairRecordMapper.updateByPrimaryKeySelective(repairRecord);
        RepairRecordResp repairRecordResp = new RepairRecordResp();
        BeanUtils.copyProperties(repairRecord , repairRecordResp);
        return repairRecordResp;
    }


    @Transactional(rollbackFor = Exception.class)
    public RepairRecordResp managerReply(RepairReplyReq repairReplyReq) throws Exception {
        TPropertyRepairRecord repairRecord = repairRecordMapper.selectByPrimaryKey(repairReplyReq.getId());
        if (null == repairRecord) {
            throw new BaseException("记录不存在");
        }
        repairRecord.setFollowStatement2(repairReplyReq.getReplyStatement());
        repairRecord.setUpdateTime(new Date());
        repairRecordMapper.updateByPrimaryKeySelective(repairRecord);
        RepairRecordResp repairRecordResp = new RepairRecordResp();
        BeanUtils.copyProperties(repairRecord , repairRecordResp);
        return repairRecordResp;
    }

}
